package net.dreamlu.iot.mqtt.broker.http;

import lombok.RequiredArgsConstructor;
import net.dreamlu.iot.mqtt.broker.enums.RedisKeys;
import net.dreamlu.iot.mqtt.broker.model.PlayTimeDto;
import net.dreamlu.iot.mqtt.broker.service.IMqttBrokerService;
import net.dreamlu.iot.mqtt.core.server.MqttServerCreator;
import net.dreamlu.iot.mqtt.core.server.http.api.MqttHttpRoute;
import net.dreamlu.iot.mqtt.core.server.http.api.code.ResultCode;
import net.dreamlu.iot.mqtt.core.server.http.api.result.Result;
import net.dreamlu.mica.redis.cache.MicaRedisCache;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.utils.hutool.StrUtil;

/**
 * @author: chenlf
 * @date: 2023/9/5
 * @description: EndpointsHttpApi
 **/
@Component
@RequiredArgsConstructor
public class PlayClientTimeHttpApi implements MqttHttpRoute, SmartInitializingSingleton {
    private final IMqttBrokerService mqttBrokerService;
    private MqttServerCreator serverCreator;
    private final ApplicationContext context;
    private final MicaRedisCache redisCache;

    @Override
    public String path() {
        return "/api/v1/playClientTime";
    }

    @Override
    public HttpResponse invoke(HttpRequest request) {
        String clientId = request.getParam("clientId");
        if (StrUtil.isBlank(clientId)) {
            return Result.fail(request, ResultCode.E101);
        }
        String key = RedisKeys.CONNECT_PLAYE_TIME.getKey(serverCreator.getNodeName() + ":" + clientId);
        String playTime = redisCache.get(key);
        PlayTimeDto playTimeDto = new PlayTimeDto();
        playTimeDto.setStartTime(playTime);
        playTimeDto.setClientId(clientId);
        return Result.ok(request, playTimeDto);
    }

    @Override
    public void afterSingletonsInstantiated() {
        this.serverCreator = context.getBean(MqttServerCreator.class);
    }
}
